package com.andova.ext

import android.os.SystemClock
import android.util.Log

const val TAG_PRINTER = "ANDOVA_PRINTER"
fun v(msg: String) = Log.v(TAG_PRINTER, msg)
fun d(msg: String) = Log.d(TAG_PRINTER, msg)
fun i(msg: String) = Log.i(TAG_PRINTER, msg)
fun w(msg: String) = Log.w(TAG_PRINTER, msg)
fun e(msg: String) = Log.e(TAG_PRINTER, msg)

private val counter = Counter()
fun printCounter(extra: String? = null) {
    val widget = counter.getAndIncrement() ?: return
    if (System.currentTimeMillis() - widget.millis >= 1000L) {
        i("count=${widget.count}, thread=${Thread.currentThread()}[${Thread.currentThread().id}], extra=${extra ?: widget}")
        counter.reset()
    }
}

fun printDelay(extra: String? = null) {
    val widget = counter.getTimeNotIncrement() ?: return
    val m = System.currentTimeMillis()
    val delay = m - widget.millis
    i("delay=$delay, thread=${Thread.currentThread()}[${Thread.currentThread().id}], extra=${extra ?: widget}")
    widget.millis = m
}

fun <R> methodTime(func: () -> R): R {
    val s = SystemClock.currentThreadTimeMillis()
    val ret = func()
    d("method time millis -> ${SystemClock.currentThreadTimeMillis() - s}")
    return ret
}

data class Widget(var count: Int, var millis: Long)
class Counter {
    private val counterMap = mutableMapOf<Long, Widget>()
    fun getTimeNotIncrement(): Widget? {
        val id = Thread.currentThread().id
        val widget = counterMap[id]
        if (widget == null) {
            counterMap[id] = Widget(1, System.currentTimeMillis())
        }
        return widget
    }

    fun getTimeAndIncrement(): Widget? {
        val id = Thread.currentThread().id
        val widget = counterMap[id]
        if (widget == null) {
            counterMap[id] = Widget(1, System.currentTimeMillis())
        } else widget.millis = System.currentTimeMillis()
        return widget
    }

    fun getAndIncrement(): Widget? {
        val id = Thread.currentThread().id
        val widget = counterMap[id]
        if (widget == null) {
            counterMap[id] = Widget(1, System.currentTimeMillis())
        } else widget.count += 1
        return widget
    }

    fun reset() {
        if (counterMap.size > 10) counterMap.remove(counterMap.keys.elementAt(0))
        val widget = counterMap[Thread.currentThread().id]
        if (widget != null) {
            widget.count = 0
            widget.millis = System.currentTimeMillis()
        }
    }
}